import { getWoInfo, woClose, woTake, getWoOperateList } from '@/api/workOrder'

const getDefaultState = () => {
  return {
    workOrderId: '',
    workOrderInfo: {},
    operateList: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // 加载 工单详情/操作记录/处理结果
  async loadWorkOrderById({ state }, id) {
    const workOrderId = id || state.workOrderId
    // 工单信息
    const { retData: WoInfo } = await getWoInfo(workOrderId)
    const { retData: woOperate } = await getWoOperateList(workOrderId)
    const { records } = woOperate || {}

    state.workOrderId = workOrderId
    state.workOrderInfo = WoInfo || {}
    state.operateList = (records || []).reverse()
  },

  // 接单
  async onWoTake({ dispatch, state }) {
    const { success } = await woTake(state.workOrderId)
    if (success) {
      dispatch('loadWorkOrderById')
    }
  },
  // 关闭并处理 - 工单
  async onWoClose({ dispatch }, payload) {
    const { success } = await woClose(
      Object.assign(
        {
          id: state.workOrderId
        },
        payload
      )
    )
    if (success) {
      dispatch('loadWorkOrderById')
    }
    return Promise.resolve(success)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
